package com.ypan.uninstaller.backup;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.FileObserver;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ypan.uninstaller.BaseFragment;
import com.ypan.uninstaller.MainApp;
import com.ypan.uninstaller.R;
import com.ypan.uninstaller.adapter.ApkInfo;
import com.ypan.uninstaller.adapter.AppListAdapter;
import com.ypan.uninstaller.logger.SLog;
import com.ypan.uninstaller.utils.DialogHelper;
import com.ypan.uninstaller.utils.PackageUtils;
import com.ypan.uninstaller.utils.SharePreferences;

/**
 * @ClassName: BackupFragment
 * @Description: BackupFragment
 * @author Administrator
 * @date 2012-8-15 下午10:54:18
 */
public class BackupFragment extends BaseFragment implements
		OnItemClickListener, onFileChangedListener {

	private static final String TAG = BackupFragment.class.getSimpleName();

	private ArrayList<String> mFilelist;

	public static final int MSG_REFRESH_DATA = 0x1000;
	public static final int MSG_INSTALL_APK = MSG_REFRESH_DATA + 1;
	public static final int MSG_DELETE_APK = MSG_REFRESH_DATA + 2;
	private static final String INSTALL_DLG = "install_dlg";
	private static final String DELETE_DLG = "delete_dlg";

	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_REFRESH_DATA:
				new BackupTask().execute(MainApp.sMainActivity);
				break;
			case MSG_INSTALL_APK: {
				int result = (Integer) msg.obj;
				if (result == 0) {
					DialogFragment installDlg = DialogHelper
							.createWaitingDialog(R.string.installing);
					showDialog(getFragmentManager(), installDlg, INSTALL_DLG);
				} else if (result == 1) {
					dismissDialog(getFragmentManager(), INSTALL_DLG);
				}
			}
				break;
			default:
				break;
			}
		}
	};

	public static BackupFragment newInstance() {
		BackupFragment fragment = new BackupFragment();
		return fragment;
	}

	private SDCardListener mListener = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mListener = new SDCardListener(this, SharePreferences.getBackupPath());
		mListener.startWatching();
	}

	@Override
	public void onDestroy() {
		if (mListener != null) {
			mListener.stopWatching();
			mListener = null;
		}
		super.onDestroy();
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		menu.clear();
		MenuItem item;
		item = menu.add(0, MENU_SEARCH, 0, R.string.search);
		item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS
				| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
		// about view
		item = menu.add(0, MENU_ABOUT, 0, R.string.about);
		item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_ABOUT:
			showAlertDialog(DIALOG_ABOUT);
			break;
		case MENU_SEARCH:
			showAlertDialog(DIALOG_SEARCH);
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return initView(inflater, container, savedInstanceState);
	}

	private void showAlertDialog(int dialogID) {
		switch (dialogID) {
		case DIALOG_ABOUT:
			DialogHelper.showAboutDialog(getFragmentManager());
			break;
		default:
			break;
		}
	}

	/**
	 * 单击处理
	 */
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		mAdapter.checkPos(position);
	}

	@Override
	public void onChange(int msg) {
		switch (msg) {
		case FileObserver.DELETE:
			mHandler.removeMessages(MSG_REFRESH_DATA);
			mHandler.sendEmptyMessageDelayed(MSG_REFRESH_DATA, 100);
			break;
		case FileObserver.CLOSE_WRITE:
			mHandler.removeMessages(MSG_REFRESH_DATA);
			mHandler.sendEmptyMessageDelayed(MSG_REFRESH_DATA, 100);
			break;

		default:
			break;
		}
	}

	private void updateDisplay(ArrayList<String> fileList) {
		mFilelist = fileList;
		boolean isEmpty = ((fileList == null) || (fileList.size() == 0));
		mLayout.setVisibility(isEmpty ? View.VISIBLE : View.GONE);
		mListView.setVisibility(isEmpty ? View.GONE : View.VISIBLE);
		if (!Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			mTv.setText(R.string.backup_list_unmount_sdcard);
		} else {
			mTv.setText(R.string.backup_list_noapk);
		}
		mApkInfoList.clear();
		for (String path : fileList) {
			mApkInfoList.add(PackageUtils.getApkInfo(path));
		}
		mAdapter.update(mApkInfoList);
	}

	class BackupTask extends AsyncTask<Context, Integer, ArrayList<String>> {

		@Override
		protected ArrayList<String> doInBackground(Context... params) {
			return getFileList();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

		@Override
		protected void onCancelled() {
			SLog.d(TAG, "onCancelled.................");
			super.onCancelled();
		}

		@Override
		protected void onPreExecute() {
			SLog.d(TAG, "onPreExecute..............");
			if (mFilelist == null && MainApp.sMainActivity != null) {
				MainApp.sMainActivity
						.setProgressBarIndeterminateVisibility(true);
			}
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(ArrayList<String> result) {
			SLog.d(TAG, "onPostExecute.................");
			if (mFilelist == null && MainApp.sMainActivity != null) {
				MainApp.sMainActivity
						.setProgressBarIndeterminateVisibility(false);
			}
			updateDisplay(result);
		}
	}

	private ArrayList<String> getFileList() {
		ArrayList<String> filelist = new ArrayList<String>();
		File file = new File(SharePreferences.getBackupPath());
		if (file != null) {
			SLog.d(TAG, "file = " + file);
			FilenameFilter filter = new FilenameFilter() {
				@Override
				public boolean accept(File dir, String filename) {
					return filename.endsWith(".apk");
				}
			};
			File[] list = file.listFiles(filter);
			if (list != null) {
				SLog.d(TAG, "list size = " + list.length);
				for (File f : list) {
					filelist.add(f.getAbsolutePath());
				}
			}
			SLog.d(TAG, "filelist size " + filelist.size());
		}
		return filelist;
	}

	private ListView mListView;
	private TextView mTv;
	private LinearLayout mLayout;
	private final ArrayList<ApkInfo> mApkInfoList = new ArrayList<ApkInfo>();
	private AppListAdapter mAdapter = null;

	private View initView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.backup, container, false);
		mTv = (TextView) view.findViewById(R.id.backup_list_noapk_text);
		mListView = (ListView) view.findViewById(R.id.backup_list);
		mLayout = (LinearLayout) view.findViewById(R.id.backup_list_noapk);
		// init mAdapter
		mAdapter = new AppListAdapter(inflater, mApkInfoList, true);
		// set Adapter of listActivity
		mListView.setAdapter(mAdapter);
		//
		mListView.setOnItemClickListener(this);
		mListView.setOnCreateContextMenuListener(this);

		return view;
	}

	@Override
	public void onUninstallClick() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				if (mAdapter != null) {
					ArrayList<ApkInfo> list = mAdapter.getCheckedList();
					if (list.size() == 0)
						return;
					Message msgstart = new Message();
					msgstart.what = MSG_INSTALL_APK;
					msgstart.obj = 0; // 开始
					mHandler.sendMessage(msgstart);
					for (ApkInfo info : list) {
						if (info != null) {
							PackageUtils.install_root(MainApp.sMainActivity,
									info.backpath, MSG_INSTALL_APK, mHandler);

						}
					}
					Message msgend = new Message();
					msgend.what = MSG_INSTALL_APK;
					msgend.obj = 1; // 结束
					mHandler.sendMessage(msgend);
				}
			}
		}).start();
	}

	@Override
	public void onSelAllClick() {
		if (mAdapter != null)
			mAdapter.checkAll();
	}

	@Override
	public void onUnSelAllClick() {
		if (mAdapter != null)
			mAdapter.uncheckAll();
	}

	@Override
	public void onDeleteClick() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				ArrayList<ApkInfo> list = mAdapter.getApkList();
				Message msgstart = new Message();
				msgstart.what = MSG_DELETE_APK;
				msgstart.obj = 0; // 开始
				mHandler.sendMessage(msgstart);
				for (ApkInfo info : list) {
					if (info != null && info.isChecked) {
						String path = info.backpath;
						File file = new File(path);
						file.delete();
					}
				}
				Message msgend = new Message();
				msgend.what = MSG_DELETE_APK;
				msgend.obj = 1; // 结束
				mHandler.sendMessage(msgend);
			}
		}).start();

	}

	@Override
	public void onLoadData(boolean bforceUpdate) {
		// 当数据没有的时候 再获取数据
		if (mFilelist == null || bforceUpdate)
			new BackupTask().execute(MainApp.sMainActivity);
	}
}
